// --------------------------录音功能---------------------

function __log(e, data) {
  log.innerHTML += "\n" + e + " " + (data || '');
}

var audio_context;
var recorder;

function startUserMedia(stream) {
  var input = audio_context.createMediaStreamSource(stream);
  __log('Media stream created.');

  // Uncomment if you want the audio to feedback directly
  //input.connect(audio_context.destination);
  //__log('Input connected to audio context destination.');

  recorder = new Recorder(input);
  __log('Recorder initialised.');
}

// 开始录音
function startRecording(button) {
  recorder && recorder.record();
  // button.disabled = true;
  // button.nextElementSibling.disabled = false;
  // __log('Recording...');
  console.log(button);
}

// 停止录音
function stopRecording(button) {
  var $this = $(this);
  recorder && recorder.stop();
  button.disabled = true;
  button.previousElementSibling.disabled = false;
  __log('Stopped recording.');

  // create WAV download link using audio data blob
  createDownloadLink();

  // recorder.clear();
  var $button = $(button);
  console.log($button);
}

function createDownloadLink() {
  recorder && recorder.exportWAV(function (blob) {
    console.log(blob)
    var url = URL.createObjectURL(blob);
    var li = document.createElement('li');
    var au = document.createElement('audio');
    var hf = document.createElement('a');

    au.controls = true;
    au.src = url;

    hf.href = url;
    hf.download = new Date().toISOString() + '.wav';
    hf.innerHTML = hf.download;
    li.appendChild(au);
    li.appendChild(hf);
    recordingslist.appendChild(li);


    blobToDataURL(blob, function (dataurl) {
      console.log(dataurl);
      // 上传语音信息
      var obj = {
        "type": 1,
        "chatRecord": {
          "id": null,
          "userid": chatId,
          "friendid": friendid,
          "message": '',
          "ext": dataurl,
          "alarmid":apkAlarmid
        }
      };
      // CHAT.chat(JSON.stringify(obj));
      chatSend.send(JSON.stringify(obj));
      // 重新加载好友快照
      loadChatSnapshot();
    });

  });


}

window.onload = function init() {
  try {
    // webkit shim
    window.AudioContext = window.AudioContext || window.webkitAudioContext;
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
    window.URL = window.URL || window.webkitURL;

    audio_context = new AudioContext;
    __log('Audio context set up.');
    __log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!'));
  } catch (e) {
    alert('No web audio support in this browser!');
  }

  navigator.getUserMedia({
    audio: true
  }, startUserMedia, function (e) {
    __log('No live audio input: ' + e);
  });
};


// 开始录音
$('#chatModal .startRecording').click(function () {
  startRecording(this);
  $('.chatStyleBox .rp').show();
});
// 停止录音
$('.chatStyleBox .stopRecording').click(function () {
  stopRecording(this);
  $('.chatStyleBox .rp').hide();
});

// 点击语音，播放
$('#chatModal').on('click', '.vioceImg', function () {
  var index = $(this).attr('index');
  var arr = loadChatSnapshotArr[index];
  var dataurl = arr.ext;
  var blob = dataURLtoBlob(dataurl);
  console.log(blob);
  var url = URL.createObjectURL(blob);
  $('#sound').attr('src', url);
});